package com.hllxd.hism.star.controller;

import com.alibaba.fastjson.JSON;
import com.bj58.zp.cdata.framework.rpc.client.basic.RpcInvoker;
import com.bj58.zp.cdata.framework.rpc.client.basic.RpcReqData;
import com.bj58.zp.cdata.framework.rpc.client.basic.RpcResData;
import com.hllxd.hism.star.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuguangxi
 * @description
 * @date 2023/11/14 19:39
 **/
@Slf4j
@RestController
@RequestMapping("/star/svc3")
public class Svc3Controller {

    @Autowired
    private RpcInvoker rpcInvoker;

    /**
     * 通用执行接口
     */
    @RequestMapping(value = "**/*.do/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object request(@PathVariable String id, HttpServletRequest request) {
        String uri = request.getRequestURI();
        log.info("param:{}, {}", uri, id);
        ServicePath sp = initServicePath(uri);
        if (sp == null) {
            log.warn("uri is invalid. {}", uri);
            return ResultUtils.errorResult("1011003", "uri is invalid.");
        }
        String traceID = "", userID = "";
        try {
            ConsoleContext context = ThreadLocalManager.getConsoleContext();
            if (context != null) {
                traceID = context.getTraceId();
                userID = request.getParameter("oa");
            } else {
                userID = "999999";
                traceID = getTraceID();
            }
            log.info("request userID: {}, traceID:{}, uri: {}", userID, traceID, uri);
            SyslogManager.product(traceID, userID, sp.service, sp.path);
            // 截取.do后面的
            sp.path = sp.path.substring(0, sp.path.indexOf(".do") + 3);
            log.info("request userID: {}, traceID:{}, path: {}, id: {}", userID, traceID, sp.path, id);

            RpcReqData reqData = buildRpcReqData(traceID, userID, sp.path, id);
            RpcResData<String> rpcResData = rpcInvoker.invoke(sp.service, reqData);
            if (rpcResData == null) {
                return ResultUtils.errorResult("1011001", "Request Service Failed.");
            }
            return ResultUtils.result(rpcResData.getCode(), rpcResData.getMessage(), JSON.parse(rpcResData.getData()));
        } catch (Exception e) {
            log.warn("Exception: {}, {}, {}", uri, id, e, e);
            return ResultUtils.errorResult("1011002", "Exception:" + e);
        }
    }

    static class ServicePath {
        public String service;
        public String path;

        public static ServicePath build(String service, String path) {
            ServicePath thiz = new ServicePath();
            thiz.service = service;
            thiz.path = path;
            return thiz;
        }
    }

    private static ServicePath initServicePath(String uri) {
        try {
            String[] items = uri.split("/");
            StringBuilder sb = new StringBuilder();
            for (int i = 4; i < items.length; ++i) {
                sb.append("/").append(items[i]);
            }
            return ServicePath.build(items[3], sb.toString());
        } catch (Exception e) {
            log.warn("Exception: {}.", e.toString());
            return null;
        }
    }

    private static RpcReqData buildRpcReqData(String traceID, String userID, String path, String id) {
        RpcReqData thiz = new RpcReqData();
        thiz.setTraceID(traceID);
        thiz.setUserID(userID);
        thiz.setPath(path);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("id", id);
        thiz.setData(paramMap);
        return thiz;
    }

    private String getTraceID() {
        String traceID;
        ConsoleContext context = ThreadLocalManager.getConsoleContext();
        if (context != null) {
            traceID = context.getTraceId();
        } else {
            traceID = TraceUtil.newTraceId();
        }
        return traceID;
    }
}
